<script setup>
import { useRouter, useRoute } from "vue-router";
import { ref, reactive, watch } from "vue";
import request from "../../utils/request";
import { ElNotification } from "element-plus";

let breadList = []; // 路由集合
const route = useRoute();
const getBreadcrumb = (url) => {
  let matched = url.matched;
  //如果不是首页
  if ("Home" == matched[0].name) {
    matched[0].meta = { title: "系统首页" };
  }
  breadList = matched;
};
watch(
  route,
  (newValue, oldValue) => {
    getBreadcrumb(newValue);
  },
  { deep: true, immediate: true }
);

const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};
// 富文本编辑器开始
let md = ref(null);
let img_file = {};
const imgs = ref([]);
const imgAdd = (pos, $file) => {
  // 缓存图片信息
  img_file[pos] = $file;
  return imgs.value.push(img_file[pos]);
};

const imgDel = (pos) => {
  delete img_file[pos];
};
// 富文本编辑器结束

const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    var formData = new FormData();
    imgs.value.forEach((e) => {
      formData.append("file", e);
    });
    formData.append("file", imgs.value);
    formData.append("traId", ruleForm.traId);
    formData.append("uId", ruleForm.uId);
    formData.append("title", ruleForm.title);
    formData.append("content", ruleForm.content);
    formData.append("desc", ruleForm.desc);
    formData.append("category", ruleForm.category);
    formData.append("like", ruleForm.like);
    formData.append("author", ruleForm.author);

    if (valid) {
      // console.log("提交更新", fields);
      request
        .post("/article/add", formData, {
          headers: {
            "Content-Type":
              "multipart/form-data;charset=UTF-8; boundary=<calculated when request is sent>",
          },
        })
        .then((res) => {
          if (res.data.code == 200) {
            ElNotification({
              title: "添加成功",
              message: "成功添加文章信息",
            });
            formEl.resetFields();
          } else {
            ElNotification({
              title: "添加失败",
              message: "请检查失败原因",
            });
          }
        })
        .catch((e) => {
          ElNotification({
            title: "添加失败",
            message: "请检查失败原因",
          });
        });
    } else {
      ElNotification({
        title: "校验失败",
        message: "请重新填写信息",
      });
    }
  });
};
const ruleForm = reactive({
  traId: "1",
  uId: "1",
  like: "0",
  title: "",
  desc: "",
  author: "",
  content: "",
  category: "",
});
const rules = reactive({
  title: [
    {
      required: true,
      message: "请输入文章标题",
      trigger: "blur",
    },
  ],
  tarId: [
    {
      required: true,
      message: "请输入对应景点ID",
      trigger: "blur",
    },
  ],
  category: [
    {
      required: true,
      message: "请输入文章类型",
      trigger: "blur",
    },
  ],
  desc: [
    {
      required: true,
      message: "请输入文章简介",
      trigger: "blur",
    },
  ],
  author: [
    {
      required: false,
      message: "请输入作者",
      trigger: "blur",
    },
  ],
});
const ruleFormRef = ref();
// const centerDialogVisible = ref(false);

// 获取新添加文章内容，然后进行替换图片地址
const getData = () => {
  request
    .request({
      url: "article/getAllart",
      method: "get",
      headers: {
        "Content-Type":
          "multipart/form-data;charset=UTF-8; boundary=<calculated when request is sent>",
      },
    })
    .then((res) => {
      const arr = res.data.data; //将所有的content存为一个数组
      //以下为取得最大——即最新的content的内容
      const maxIndex = arr.reduce((maxIndex, currentValue, currentIndex) => {
        if (currentValue.artId > arr[maxIndex].artId) {
          return currentIndex;
        } else {
          return maxIndex;
        }
      }, 0);

      const content = arr[maxIndex].content;
      console.log(content);
      // console.log(res.data.data);
      return content;
    })
    .catch((e) => {
      console.log(e);
    });
};
</script>

<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item
          v-for="(item, index) in breadList"
          :key="index"
          :to="{ path: item.path }"
          >{{ item.meta.title }}</el-breadcrumb-item
        >
      </el-breadcrumb>
    </div>
    <div class="container">
      <div>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          status-icon
        >
          <el-form-item label="标题" prop="title">
            <el-input v-model="ruleForm.title" />
          </el-form-item>
          <el-form-item label="简介" prop="desc">
            <el-input v-model="ruleForm.desc" />
          </el-form-item>
          <el-form-item label="文章类型" prop="category">
            <el-select v-model="ruleForm.category" placeholder="请选择文章类型">
              <el-option label="景点介绍" value="景点介绍" />
              <el-option label="导游指南" value="导游指南" />
              <el-option label="美食文化" value="美食文化" />
              <el-option label="酒店住宿" value="酒店住宿" />
              <el-option label="旅行安全健康" value="旅行安全健康" />
              <el-option label="文化活动" value="文化活动" />
              <el-option label="最新旅游资讯" value="最新旅游资讯" />
            </el-select>
          </el-form-item>
          <el-form-item label="作者" prop="author">
            <el-input v-model="ruleForm.author" />
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <mavon-editor
              v-model="ruleForm.content"
              scrollStyle="true"
              style="width: 100%"
              ref="md"
              @imgAdd="imgAdd"
              @imgDel="imgDel"
            />
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-button type="primary" @click="submitForm(ruleFormRef)"
          >新增</el-button
        >
        <el-button @click="resetForm(ruleFormRef)">重置表单</el-button>
      </div>
    </div>
  </div>
</template>

<style scoped></style>
